package com.ruoyi.basebill.task;


import com.ruoyi.basebill.domain.*;
import com.ruoyi.basebill.service.impl.OmsPurinwarehsbillServiceImpl;
import com.ruoyi.basebill.service.impl.OmsReceiptbillServiceImpl;
import com.ruoyi.basebill.service.impl.OmsSaleissuebillServiceImpl;
import com.ruoyi.basebill.service.impl.OmsStocktransferbillServiceImpl;
import com.ruoyi.basebill.task.util.OmsTaskUtil;
import com.ruoyi.basedata.domain.BdCustomer;
import com.ruoyi.basedata.domain.BdSupplier;
import com.ruoyi.basedata.domain.BdWarehouse;
import com.ruoyi.basedata.domain.OmsOrgunit;
import com.ruoyi.basedata.service.impl.BdCustomerServiceImpl;
import com.ruoyi.basedata.service.impl.BdSupplierServiceImpl;
import com.ruoyi.basedata.service.impl.BdWarehouseServiceImpl;
import com.ruoyi.basedata.service.impl.OmsOrgunitServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component("OmsReceiptBillTaskNew")
public class OmsReceiptBillTaskNew {

    //收货确认服务层接口
    @Autowired
    private OmsReceiptbillServiceImpl receiptbillService;

    //销售出库单服务层接口
    @Autowired
    private OmsSaleissuebillServiceImpl saleissuebillService;

    //采购入库单服务层接口
    @Autowired
    private OmsPurinwarehsbillServiceImpl purinwarehsbillService;

    //库存调拨单服务层接口
    @Autowired
    private OmsStocktransferbillServiceImpl stocktransferbillService;

    //仓库接口
    @Autowired
    private BdWarehouseServiceImpl warehouseService;

    //结算组织服务层接口
    @Autowired
    private OmsOrgunitServiceImpl orgunitService;

    //客户服务层接口
    @Autowired
    private BdCustomerServiceImpl customerService;

    //供应商接口
    @Autowired
    private BdSupplierServiceImpl supplierService;

    //定时任务工具类
    @Autowired
    private OmsTaskUtil omsTaskUtil;

    //注入自己
    @Autowired
    private OmsReceiptBillTaskNew receiptBillTask;

    public void pushDown() {
        List<OmsReceiptbill> omsReceiptbills = receiptbillService.selectPushDownBill();
        if (StringUtils.isEmpty(omsReceiptbills)) {
            return;
        }
        for (OmsReceiptbill receiptbill : omsReceiptbills) {
            OmsReceiptbill receiptbill1 = receiptBillTask.pushDownMethod(receiptbill);
            receiptbillService.updateOmsReceiptbill(receiptbill1);
        }


    }

    public void pushDownOut() {
        List<OmsReceiptbill> omsReceiptbills = receiptbillService.selectPushDownOutSaleBill();
        if (StringUtils.isEmpty(omsReceiptbills)) {
            return;
        }
        for (OmsReceiptbill receiptbill : omsReceiptbills) {
            OmsReceiptbill omsReceiptbill1 = receiptBillTask.pushDownOutSaleBill(receiptbill);
            receiptbillService.updateOmsReceiptbill(omsReceiptbill1);
        }
    }


    /**
     * 收货确认下发生成单据
     * @param receiptbill
     * @return
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public OmsReceiptbill pushDownMethod(OmsReceiptbill receiptbill) {
        try {
            //此处需要还原对象
            receiptbill = receiptbillService.selectOmsReceiptbillById(receiptbill.getId());
            StringBuffer stringBuffer = new StringBuffer();
            try {
                //空值校验判断
                receiptBillTask.JudgeNullValues(receiptbill, stringBuffer);
            }catch (Exception e){
                throw new RuntimeException("[收货确认空值校验时出现异常：]" + e.getMessage());
            }
            String customercode = receiptbill.getCustomercode();
            BdCustomer bdCustomer = new BdCustomer();
            bdCustomer.setCustomernumber(customercode);
            List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
            bdCustomer = bdCustomers.get(0);
            Long isinternal = bdCustomer.getIsinternal();
            Long iscostcenter = bdCustomer.getIscostcenter();
            //判断是否内部客户
            boolean isOutCustomer = isinternal.equals(0L) && iscostcenter.equals(0L);
            String invoicecode = receiptbill.getInvoicecode();
            //根据组织服务层接口获取销售组织数据
            OmsOrgunit invoiceUnit = new OmsOrgunit();
            invoiceUnit.setOrgnumber(invoicecode);
            List<OmsOrgunit> omsOrgunits = orgunitService.selectOmsOrgunitList(invoiceUnit);
            //将销售组织对象存储
            invoiceUnit = omsOrgunits.get(0);

            String inventoryorganizationcode = receiptbill.getInventoryorganizationcode();
            //根据组织服务层接口获取发货组织数据
            OmsOrgunit inventoryUnit = new OmsOrgunit();
            inventoryUnit.setOrgnumber(inventoryorganizationcode);
            omsOrgunits = orgunitService.selectOmsOrgunitList(inventoryUnit);
            //将发货组织对象存储
            inventoryUnit = omsOrgunits.get(0);
            //如果销出组织等于采入组织
            if (invoicecode.equals(inventoryorganizationcode)) {
                if (isinternal.equals(1L) || iscostcenter.equals(1L)) {
                    try {
                    //生成一张库存调拨单
                    receiptBillTask.createFirstOrgSTBill(inventoryUnit, bdCustomer, receiptbill, stringBuffer);
                    }catch (Exception e){
                        throw new RuntimeException("[生成库存调拨单时出现异常：]" + e.getMessage());
                    }
                }
                receiptbill.setIscreatebill(1l);
                receiptbill.setReason("");
                return receiptbill;
            }

            HashMap<String, OmsOrgunit> twoPointOrg;
            try {
                //确定退货的最终节点和销售的最初节点
                twoPointOrg = receiptBillTask.identifyTwoNodes(inventoryUnit, invoiceUnit,"receipt");
            }catch (Exception e){
                throw new RuntimeException("[获取退货的最终节点和销售的最初节点出现异常：]" + e.getMessage());
            }
            //退货的最终节点
            OmsOrgunit returnFinalNode = twoPointOrg.get("returnFinalNode");
            //销售的最初节点
            OmsOrgunit salesInitialNode = twoPointOrg.get("salesInitialNode");
            try {
                //库存组织开始向上退货
                receiptBillTask.inventoryReturn(receiptbill,inventoryUnit,returnFinalNode);
            }catch (Exception e){
                throw new RuntimeException("[库存组织向上退货时出现异常：]" + e.getMessage());
            }
            try{
                //一级组织之间的销出采入单
                receiptBillTask.createFirstNodeBill(receiptbill,inventoryUnit,invoiceUnit);
            }catch (Exception e){
                throw new RuntimeException("[生成一级组织之间的销出采入单时出现异常：]" + e.getMessage());
            }
            try {
                //销售的最初节点向下销售
                receiptBillTask.sellDown(receiptbill,invoiceUnit,salesInitialNode);
            }catch (Exception e){
                throw new RuntimeException("[生成销售最初节点向下的销出采入单时出现异常：]" + e.getMessage());
            }
            try {
                //如果是内部客户，销售组织的中转仓不等于收获仓，生成调拨单
                receiptBillTask.transferToReceipt(invoiceUnit,bdCustomer,receiptbill,isOutCustomer,stringBuffer);
            }catch (Exception e){
                throw new RuntimeException("[销售组织的中转仓到收货仓生成调拨单时出现异常]" + e.getMessage());
            }
            receiptbill.setIscreatebill(1l);
            receiptbill.setReason("");
            return receiptbill;

//            //得到销售组织的一级组织，判断是否等于库存组织，如果不相等就需要生成对应一级组织之间的销出、采入单。
//            if (!invoiceUnit.getFirstorgnumber().equals(inventoryorganizationcode)) {
//                String firstorgnumber = invoiceUnit.getFirstorgnumber();
//                OmsOrgunit firstOrg = new OmsOrgunit();
//                firstOrg.setOrgnumber(firstorgnumber);
//                List<OmsOrgunit> omsOrgunits1 = orgunitService.selectOmsOrgunitList(firstOrg);
//                if (StringUtils.isEmpty(omsOrgunits1)) {
//                    stringBuffer.append("[没有找到组织编号为：" + firstorgnumber + " 的组织]");
//                    //手动回滚事务
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    receiptbill.setIscreatebill(-1L);
//                    receiptbill.setReason(stringBuffer.toString());
//                    return receiptbill;
//                }
//                firstOrg = omsOrgunits1.get(0);
//                //生成对应的库存组织的销出和一级组织的采入单
//                int i = omsTaskUtil.createFirstSIBillAndPWBill(inventoryUnit, firstOrg, receiptbill, bdCustomer, stringBuffer);
//                if (i == 0) {
//                    //手动回滚事务
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    receiptbill.setIscreatebill(-1L);
//                    receiptbill.setReason(stringBuffer.toString());
//                    return receiptbill;
//                }
//            }
//            //判断销售组织是否是一级组织，不是则生成销售组织的一级组织到销售组织之间的销出采入单；是则跳过
//            if (!invoiceUnit.getLevel().equals(1L)) {
//            //准备一个集合，用来存储中间过度的组织,统一用于后续生成采入销出单
//            //先获取销售组织的一级组织，记为firstOrg
//            //再获取销售组织的上级组织，记为fatherOrg
//            //开始循环,使用while循环,判断条件为firstOrg与fatherOrg是否相等
//            //循环内容为：获取fatierOrg的上级组织，并将值赋值给
//            //如果不相同则将fatherOrg加入到集合中
//            //如果相等结束循环。
//            //将一级组织生成销出单，销售组织生成采入单
//            //过渡组织集合生成采入、销出单
//
//            ArrayList<OmsOrgunit> transitionOrg = new ArrayList<>();
//            String firstOrg = invoiceUnit.getFirstorgnumber();
//            OmsOrgunit firstOrgUnit = new OmsOrgunit();
//            firstOrgUnit.setOrgnumber(firstOrg);
//            List<OmsOrgunit> firstOrgUnits = orgunitService.selectOmsOrgunitList(firstOrgUnit);
//            if (StringUtils.isEmpty(firstOrgUnits)) {
//                stringBuffer.append("[没有找到组织：" + firstOrg + "]");
//                //手动回滚事务
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                receiptbill.setIscreatebill(-1L);
//                receiptbill.setReason(stringBuffer.toString());
//                return receiptbill;
//            }
//            firstOrgUnit = firstOrgUnits.get(0);
//            String parentorgnumber = invoiceUnit.getParentorgnumber();
//            OmsOrgunit parentUnit = new OmsOrgunit();
//            parentUnit.setOrgnumber(parentorgnumber);
//            List<OmsOrgunit> omsOrgunits1 = orgunitService.selectOmsOrgunitList(parentUnit);
//            if (StringUtils.isEmpty(omsOrgunits1)) {
//                stringBuffer.append("[没有找到组织：" + parentorgnumber + "]");
//                //手动回滚事务
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                receiptbill.setIscreatebill(-1L);
//                receiptbill.setReason(stringBuffer.toString());
//                return receiptbill;
//            }
//            parentUnit = omsOrgunits1.get(0);
//            while (!firstOrg.equals(parentorgnumber)) {
//                transitionOrg.add(0, parentUnit);
//                OmsOrgunit tempOrgUnit = new OmsOrgunit();
//                tempOrgUnit.setOrgnumber(parentUnit.getParentorgnumber());
//                List<OmsOrgunit> tempOrgUnits = orgunitService.selectOmsOrgunitList(tempOrgUnit);
//                if (StringUtils.isEmpty(tempOrgUnits)) {
//                    stringBuffer.append("[没有找到组织：" + tempOrgUnit.getOrgnumber() + "]");
//                    //手动回滚事务
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    receiptbill.setIscreatebill(-1L);
//                    receiptbill.setReason(stringBuffer.toString());
//                    return receiptbill;
//                }
//                parentUnit = tempOrgUnits.get(0);
//                parentorgnumber = parentUnit.getOrgnumber();
//            }
//            transitionOrg.add(0, firstOrgUnit);
//            transitionOrg.add(invoiceUnit);
//            //依次将两个组织传入方法进行生成销出采入单
//            for (int i = 0; i < transitionOrg.size() - 1; i++) {
//                int insertResult = omsTaskUtil.createTransitionSIBillAndPWBill(transitionOrg.get(i), transitionOrg.get(i + 1), receiptbill, bdCustomer, stringBuffer);
//                if (insertResult == 0) {
//                    //手动回滚事务
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    receiptbill.setIscreatebill(-1L);
//                    receiptbill.setReason(stringBuffer.toString());
//                    return receiptbill;
//                }
//            }
//            }
//            //如果是内部客户，销售组织的中转仓不等于收获仓，生成调拨单
//            if (!isOutCustomer){
//                String transferwhnumber = invoiceUnit.getTransferwhnumber();
//                String receivefacilitycode = receiptbill.getReceivefacilitycode();
//                if (!transferwhnumber.equals(receivefacilitycode)){
//                    //生成一张调拨单，由中转仓调拨到收获仓
//                    int insetResult = omsTaskUtil.createInvoiceUnitTransferBill(invoiceUnit, bdCustomer, receiptbill, stringBuffer);
//                    if (insetResult == 0){
//                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                        receiptbill.setIscreatebill(-1L);
//                        receiptbill.setReason(stringBuffer.toString());
//                        return receiptbill;
//                    }
//                }
//            }
//
//            receiptbill.setIscreatebill(1l);
//            receiptbill.setReason("");
//            return receiptbill;
        } catch (Exception e) {
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            receiptbill.setIscreatebill(-1L);
            receiptbill.setReason(e.getMessage());
            return receiptbill;
        }
    }


    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public OmsReceiptbill pushDownOutSaleBill(OmsReceiptbill receiptbill) {
        //此处需要还原对象
        receiptbill = receiptbillService.selectOmsReceiptbillById(receiptbill.getId());
        StringBuffer stringBuffer = new StringBuffer();
        //空值校验判断
        int i1 = omsTaskUtil.JudgeNullValues(receiptbill, stringBuffer);
        if (i1 == 0) {
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            receiptbill.setIscreatebill(-1L);
            receiptbill.setReason(stringBuffer.toString());
            return receiptbill;
        }
        String customercode = receiptbill.getCustomercode();
        BdCustomer bdCustomer = new BdCustomer();
        bdCustomer.setCustomernumber(customercode);
        List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
        bdCustomer = bdCustomers.get(0);
        Long isinternal = bdCustomer.getIsinternal();
        Long iscostcenter = bdCustomer.getIscostcenter();
        boolean isOutCustomer = isinternal.equals(0L) && iscostcenter.equals(0L);
        if (isOutCustomer) {
            //生成一张对外的销售出库单
            int i = omsTaskUtil.createForeignSaleIssueBill(receiptbill, stringBuffer);
            if (i == 0) {
                //手动回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                receiptbill.setIscreateoutbill(-1L);
                receiptbill.setOutreason(stringBuffer.toString());
                return receiptbill;
            }
            receiptbill.setIscreateoutbill(1L);
            return receiptbill;
        }
        receiptbill.setIscreateoutbill(-2L);
        return receiptbill;
    }


    /**
     * 对传入的收货确认单进行非空字段的校验
     * @param receiptbill 收货确认单
     * @param stringBuffer 错误信息
     * @return 结果
     */
    public void JudgeNullValues(OmsReceiptbill receiptbill,StringBuffer stringBuffer){
        boolean isEmpty = false;
        boolean isNull = false;
        String code = receiptbill.getCode();
        if (StringUtils.isEmpty(code)) {
            stringBuffer.append("[销售收货单号为空]");
            isEmpty = true;
        }
        String srcSys = receiptbill.getSrcsys();
        if (StringUtils.isEmpty(srcSys)) {
            stringBuffer.append("[来源系统为空]");
            isEmpty = true;
        }
        String shipmentcode = receiptbill.getShipmentcode();
        if (StringUtils.isEmpty(shipmentcode)) {
            stringBuffer.append("[发货单号为空]");
            isEmpty = true;
        }
        String customercode = receiptbill.getCustomercode();
        if (StringUtils.isEmpty(customercode)) {
            stringBuffer.append("[客户编码为空]");
            isEmpty = true;
        }
        String invoicecode = receiptbill.getInvoicecode();
        if (StringUtils.isEmpty(invoicecode)) {
            stringBuffer.append("[销售组织编码为空]");
            isEmpty = true;
        }
        String costcentercode = receiptbill.getCostcentercode();
        if (StringUtils.isEmpty(costcentercode)) {
            stringBuffer.append("[成本中心编码为空]");
            isEmpty = true;
        }
//        String saleswarehousecode = receiptbill.getSaleswarehousecode();
//        if (StringUtils.isEmpty(saleswarehousecode)) {
//            stringBuffer.append("[销售组织仓库编码为空]");
//            isEmpty = true;
//        }
        String inventoryorganizationcode = receiptbill.getInventoryorganizationcode();
        if (StringUtils.isEmpty(inventoryorganizationcode)) {
            stringBuffer.append("[库存组织编码为空]");
            isEmpty = true;
        }
        String facilitycode = receiptbill.getFacilitycode();
        if (StringUtils.isEmpty(facilitycode)) {
            stringBuffer.append("[发货仓库编码为空]");
            isEmpty = true;
        }
        Date receiptdate = receiptbill.getReceiptdate();
        if (StringUtils.isNull(receiptdate)) {
            stringBuffer.append("[收货日期为空]");
            isEmpty = true;
        }
        String currency = receiptbill.getCurrency();
        if (StringUtils.isEmpty(currency)) {
            stringBuffer.append("[币别为空]");
            isEmpty = true;
        }
        BigDecimal exchangerate = receiptbill.getExchangerate();
        if (StringUtils.isNull(exchangerate)) {
            stringBuffer.append("[汇率为空]");
            isEmpty = true;
        }

        if (isEmpty) {
            throw new RuntimeException('[' + stringBuffer.toString() + ']');
        }

        BdCustomer bdCustomer = new BdCustomer();
        bdCustomer.setCustomernumber(customercode);
        List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
        if (StringUtils.isEmpty(bdCustomers)) {
            stringBuffer.append("[没有找到客户：" + customercode + ']');
            isNull = true;
        }else {
            bdCustomer = bdCustomers.get(0);
            Long isinternal = bdCustomer.getIsinternal();
            Long iscostcenter = bdCustomer.getIscostcenter();
            if (isinternal.equals(1L) || iscostcenter.equals(1L)){
                //内部客户，则收货仓库需要校验
                String receivefacilitycode = receiptbill.getReceivefacilitycode();
                if (StringUtils.isEmpty(receivefacilitycode)){
                    stringBuffer.append("[收货仓库编码为空]");
                    isNull = true;
                }
            }
        }

        OmsOrgunit omsOrgunit = new OmsOrgunit();
        omsOrgunit.setOrgnumber(invoicecode);
        List<OmsOrgunit> omsOrgunits = orgunitService.selectOmsOrgunitList(omsOrgunit);
        if (StringUtils.isEmpty(omsOrgunits)) {
            stringBuffer.append("[没有找到销售组织：" + invoicecode + ']');
            isNull = true;
        }
        BdWarehouse bdWarehouse = new BdWarehouse();
//        bdWarehouse.setWarehousenumber(saleswarehousecode);
        List<BdWarehouse> bdWarehouses;
//        if (StringUtils.isEmpty(bdWarehouses)) {
//            stringBuffer.append("[没有找到仓库：" + saleswarehousecode + ']');
//            isNull = true;
//        }
        omsOrgunit.setOrgnumber(inventoryorganizationcode);
        omsOrgunits = orgunitService.selectOmsOrgunitList(omsOrgunit);
        if (StringUtils.isEmpty(omsOrgunits)) {
            stringBuffer.append("[没有找到库存组织：" + inventoryorganizationcode + ']');
            isNull = true;
        }
        bdWarehouse.setWarehousenumber(facilitycode);
        bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
        if (StringUtils.isEmpty(bdWarehouses)) {
            stringBuffer.append("[没有找到发货仓库：" + facilitycode + ']');
            isNull = true;
        }
        if (isNull) {
            throw new RuntimeException('[' + stringBuffer.toString() + ']');
        }
        //判断分录中是否符合要求
        List<OmsReceiptbillentry> omsReceiptbillentryList = receiptbill.getOmsReceiptbillentryList();
        if (StringUtils.isEmpty(omsReceiptbillentryList)) {
            stringBuffer.append("[分录为空！]");
            throw new RuntimeException('[' + stringBuffer.toString() + ']');
        }
        JudgeEntryNullValues(omsReceiptbillentryList, stringBuffer);
    }

    /**
     * 对传入的收货确认单分录集合进行非空字段的校验
     * @param omsReceiptbillentryList 收货确认单分录
     * @param stringBuffer 错误信息
     * @return 结果
     */
    public void JudgeEntryNullValues(List<OmsReceiptbillentry> omsReceiptbillentryList, StringBuffer stringBuffer) {
        boolean isEmpty = false;
        for (int i = 0; i < omsReceiptbillentryList.size(); i++) {
            OmsReceiptbillentry omsReceiptbillentry = omsReceiptbillentryList.get(i);
            if (StringUtils.isEmpty(omsReceiptbillentry.getSkucode())) {
                stringBuffer.append("[第" + i + 1 + "条分录" + "商品编号为空]");
                isEmpty = true;
            }
            if (StringUtils.isNull(omsReceiptbillentry.getReceivedqty())) {
                stringBuffer.append("[第" + i + 1 + "条分录" + "实收数量为空]");
                isEmpty = true;
            }
            if (StringUtils.isEmpty(omsReceiptbillentry.getUnit())) {
                stringBuffer.append("[第" + i + 1 + "条分录" + "计量单位编码为空]");
                isEmpty = true;
            }
            if (StringUtils.isNull(omsReceiptbillentry.getBasereceivedqty())) {
                stringBuffer.append("[第" + i + 1 + "条分录" + "基本实收数量为空]");
                isEmpty = true;
            }
            if (StringUtils.isEmpty(omsReceiptbillentry.getBaseunit())) {
                stringBuffer.append("[第" + i + 1 + "条分录" + "基本计量单位为空]");
                isEmpty = true;
            }
            if (StringUtils.isNull(omsReceiptbillentry.getNotaxprice())) {
                stringBuffer.append("[第" + i + 1 + "条分录" + "不含税单价为空]");
                isEmpty = true;
            }
            if (StringUtils.isNull(omsReceiptbillentry.getNotaxamount())) {
                stringBuffer.append("[第" + i + 1 + "条分录" + "不含税总金额为空]");
                isEmpty = true;
            }
            if (StringUtils.isNull(omsReceiptbillentry.getTaxprice())) {
                stringBuffer.append("[第" + i + 1 + "条分录" + "含税单价为空]");
                isEmpty = true;
            }
            if (StringUtils.isNull(omsReceiptbillentry.getTaxamount())) {
                stringBuffer.append("[第" + i + 1 + "条分录" + "含税总金额为空]");
                isEmpty = true;
            }
            if (StringUtils.isNull(omsReceiptbillentry.getIsgift())) {
                stringBuffer.append("[第" + i + 1 + "条分录" + "是否赠品为空]");
                isEmpty = true;
            }
        }
        if (isEmpty) {
            throw new RuntimeException('[' + stringBuffer.toString() + ']');
        }
    }


    /**
     * 传入库存组织、客户、收货确认单 生成一张库存调拨单
     * @param inventoryUnit 库存组织
     * @param bdCustomer 客户
     * @param receiptbill 收货确认单
     * @param stringBuffer 错误信息
     * @return 生成结果
     */
    public void createFirstOrgSTBill(OmsOrgunit inventoryUnit, BdCustomer bdCustomer, OmsReceiptbill receiptbill, StringBuffer stringBuffer) {
        OmsStocktransferbill omsStocktransferbill = new OmsStocktransferbill();
        // 开始设置单据头数据

        //业务日期
        omsStocktransferbill.setBizdate(receiptbill.getReceiptdate());
        //单据编号
        String billNumber = omsTaskUtil.setBillNumber(omsStocktransferbill);
        omsStocktransferbill.setBillnumber(billNumber);
        //业务类型
        omsStocktransferbill.setBiztypenumber("331");
        omsStocktransferbill.setBiztypename("跨仓库调拨（成本价）");
        //获取库存组织
        String orgnumber = inventoryUnit.getOrgnumber();
        String orgname = inventoryUnit.getOrgname();
        //调出仓库组织
        omsStocktransferbill.setIssuestorageorgnumber(orgnumber);
        omsStocktransferbill.setIssuestorageorgname(orgname);
        //调入库存组织
        omsStocktransferbill.setReceiptstorageorgnumber(orgnumber);
        omsStocktransferbill.setReceiptstorageorgname(orgname);
        //调出成本中心
//        omsStocktransferbill.setOutcostcenternumber(receiptbill.getCostcentercode());
//        omsStocktransferbill.setOutcostcentername(receiptbill.getCostcentername());
        //调出记账公司
//        omsStocktransferbill.setOutaccountcompanynumber(orgnumber);
//        omsStocktransferbill.setOutaccountcompanyname(orgname);
        //调入成本中心
//        String costcenternumber = bdCustomer.getCostcenternumber();
//        if (StringUtils.isEmpty(costcenternumber)) {
//            stringBuffer.append("[客户：" + bdCustomer.getCustomernumber() + " 的成本中心为空！]");
//            return 0;
//        }
//        omsStocktransferbill.setIncostcenternumber(costcenternumber);
//        omsStocktransferbill.setIncostcentername(bdCustomer.getCostcentername());
        //调入记账公司
//        omsStocktransferbill.setInaccountcompanynumber(orgnumber);
//        omsStocktransferbill.setInaccountcompanyname(orgname);
        //币别
        omsStocktransferbill.setCurrency(receiptbill.getCurrency());
        //汇率
        omsStocktransferbill.setExchangerate(receiptbill.getExchangerate());
        //来源单据
        omsStocktransferbill.setSrcbilltype("收货确认");
        omsStocktransferbill.setSrcbillnumber(receiptbill.getCode());
        //备注
        omsStocktransferbill.setDescription(receiptbill.getBuyernote());
        //创建时间
        omsStocktransferbill.setCreatetime(new Date());
        //来源系统
        omsStocktransferbill.setSrcsys(receiptbill.getSrcsys());

        //设置分录数据
        ArrayList<OmsStocktransferbillentry> stocktransferbillentries = new ArrayList<>();
        for (OmsReceiptbillentry omsReceiptbillentry : receiptbill.getOmsReceiptbillentryList()) {
            OmsStocktransferbillentry omsStocktransferbillentry = new OmsStocktransferbillentry();
            //物料
            omsStocktransferbillentry.setMaterialnumber(omsReceiptbillentry.getSkucode());
            omsStocktransferbillentry.setMaterialname(omsReceiptbillentry.getSkuname());
            //调出仓库，获取调出仓库的在途仓库
            String facilitycode = receiptbill.getFacilitycode();
            BdWarehouse bdWarehouse = new BdWarehouse();
            bdWarehouse.setWarehousenumber(facilitycode);
            List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
            bdWarehouse = bdWarehouses.get(0);
            String transferwhnumber = bdWarehouse.getTransferwhnumber();
            if (StringUtils.isEmpty(transferwhnumber)){
                stringBuffer.append("[单据头发货仓库：" + facilitycode + "无在途仓]");
                throw new RuntimeException(stringBuffer.toString());
            }
            omsStocktransferbillentry.setIssuewarehousenumber(transferwhnumber);
            omsStocktransferbillentry.setIssuewarehousename(bdWarehouse.getTransferwhname());
            //调入仓库
            omsStocktransferbillentry.setReceiptwarehousenumber(receiptbill.getReceivefacilitycode());
            omsStocktransferbillentry.setReceiptwarehousename(receiptbill.getReceivefacilityname());
            //计量单位
            omsStocktransferbillentry.setUnitnumber(omsReceiptbillentry.getUnit());
            //基本计量单位
            omsStocktransferbillentry.setBaseunitnumber(omsReceiptbillentry.getBaseunit());
            //数量
            omsStocktransferbillentry.setQty(omsReceiptbillentry.getReceivedqty());
            //基本单位数量
            omsStocktransferbillentry.setBaseqty(omsReceiptbillentry.getBasereceivedqty());
            //计划调出日期
            omsStocktransferbillentry.setIssueplandate(receiptbill.getReceiptdate());
            //计划调入日期
            omsStocktransferbillentry.setReceiptplandate(receiptbill.getReceiptdate());
            //赠品
            omsStocktransferbillentry.setIspresent(omsReceiptbillentry.getIsgift());

            stocktransferbillentries.add(omsStocktransferbillentry);
        }
        omsStocktransferbill.setOmsStocktransferbillentryList(stocktransferbillentries);
        try {
        int i = stocktransferbillService.insertOmsStocktransferbill(omsStocktransferbill);
        if (i == 0) {
            throw new RuntimeException();
        }
    }catch (Exception e){
            stringBuffer.append("[插入库存调拨单时出现错误！]");
            throw new RuntimeException(stringBuffer.toString() + e.getMessage());
        }
    }



    /**
     * @param inventoryOrg
     * @param salesOrg
     * @param type 判断是收货下发还是退货下发
     * 确定退货和的最终节点和销售的最初节点
     * @return 存储了两个节点
     */
    public HashMap<String,OmsOrgunit> identifyTwoNodes(OmsOrgunit inventoryOrg,OmsOrgunit salesOrg,String type){
        //查看两个节点的一级组织是否相等
        String inventoryFirstorgnumber = inventoryOrg.getFirstorgnumber();
        String salesFirstorgnumber = salesOrg.getFirstorgnumber();
        OmsOrgunit inventoryFirstOrg = omsTaskUtil.getFirstOrg(inventoryOrg.getOrgnumber());
        OmsOrgunit salesFirstOrg = omsTaskUtil.getFirstOrg(salesOrg.getOrgnumber());
        if ((StringUtils.isNull(inventoryFirstOrg) || StringUtils.isNull(salesFirstOrg))){
            if("receipt".equals(type)){
                throw new RuntimeException("调出或调入组织的一级组织为空");

            }else{
                throw new RuntimeException("发货组织或结算组织的一级组织为空");
            }
        }
        //退货最终节点
        OmsOrgunit returnFinalNode;
        OmsOrgunit salesInitialNode;
        //如果销出组织和采入组织的一级组织相同
        if (inventoryFirstOrg.getOrgnumber().equals(salesFirstOrg.getOrgnumber())){
            OmsOrgunit orgNode = omsTaskUtil.getOrgNode(inventoryOrg, salesOrg);
            returnFinalNode = orgNode;
            salesInitialNode = orgNode;
        }else {
            returnFinalNode = inventoryFirstOrg;
            salesInitialNode = salesFirstOrg;
        }

        HashMap<String, OmsOrgunit> map = new HashMap<>();
        map.put("returnFinalNode",returnFinalNode);
        map.put("salesInitialNode",salesInitialNode);
        return map;
    }


    public void inventoryReturn(OmsReceiptbill receiptbill,OmsOrgunit inventoryUnit,OmsOrgunit returnFinalNode){
        //如果库存组织等于退货的最终节点，直接结束方法
        if (inventoryUnit.getOrgnumber().equals(returnFinalNode.getOrgnumber())){
            return;
        }
        //获取所有的节点组织
        ArrayList<OmsOrgunit> allTransOrg;
        try {
            allTransOrg = receiptBillTask.getAllTransOrg(inventoryUnit,returnFinalNode);
        }catch (Exception e){
            throw new RuntimeException("[获取库存组织到退货的最终节点的组织集合时出现异常：]" + e.getMessage());
        }
        //依次将两个组织传入方法进行生成销出采入单
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = allTransOrg.size() - 2; i >= 0 ; i--) {
            try {
                //这里需要确定仓库的数据来源
                receiptBillTask.createTransitionRedSIBillAndPWBill(allTransOrg.get(i), allTransOrg.get(i + 1), receiptbill, stringBuffer);
            }catch (Exception e){
                throw new RuntimeException("[生成库存组织到退货最终节点过程中的销出采入单时出现异常]" + e.getMessage());
            }
        }
    }


    /**
     * 红字
     * 传入收货确认单、库存组织、销售组织，生成销售出货单和采购入库单
     * 生成中间过渡的红字销出采入单
     * @param inventoryUnit 库存组织
     * @param invoiceUnit   销售组织
     * @param receiptbill   收货确认单
     * @param stringBuffer  错误信息
     * @return 生成信息
     */
    public void createTransitionRedSIBillAndPWBill(OmsOrgunit inventoryUnit, OmsOrgunit invoiceUnit, OmsReceiptbill receiptbill, StringBuffer stringBuffer) {
        OmsSaleissuebill omsSaleissuebill = new OmsSaleissuebill();
        OmsPurinwarehsbill omsPurinwarehsbill = new OmsPurinwarehsbill();
        /*设置销出单单据头数据*/

        //业务日期
        omsSaleissuebill.setBizdate(receiptbill.getReceiptdate());
        String billNumber = omsTaskUtil.setBillNumber(omsSaleissuebill);
        //单据编号
        omsSaleissuebill.setBillnumber(billNumber);
        //库存组织
        omsSaleissuebill.setStorageorgnumber(inventoryUnit.getOrgnumber());
        omsSaleissuebill.setStorageorgname(inventoryUnit.getOrgname());
        //业务类型
        omsSaleissuebill.setBiztypenumber("211");
        omsSaleissuebill.setBiztypename("普通销售退货");
        //事务类型
        omsSaleissuebill.setTransactiontypenumber("013");
        omsSaleissuebill.setTransactiontypename("成本出库退货");
        //获取送货客户
        String invoiceUnitNumber = invoiceUnit.getOrgnumber();
        BdCustomer bdCustomer = new BdCustomer();
        bdCustomer.setInternalcompanynumber(invoiceUnitNumber);
        List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
        if (StringUtils.isEmpty(bdCustomers)) {
            stringBuffer.append("[没有找到内部公司编码为：" + invoiceUnitNumber + "的客户]");
            throw new RuntimeException(stringBuffer.toString());
        }
        bdCustomer = bdCustomers.get(0);
        //设置送货客户
        omsSaleissuebill.setCustomernumber(bdCustomer.getCustomernumber());
        omsSaleissuebill.setCustomername(bdCustomer.getCustomername());
        //记账公司
        omsSaleissuebill.setAccountcompanynumber(inventoryUnit.getOrgnumber());
        omsSaleissuebill.setAccountcompanyname(inventoryUnit.getOrgname());
        //成本中心
        omsSaleissuebill.setCostcenternumber("1.91");
        omsSaleissuebill.setCostcentername("关联单位");
        //币别
//        omsSaleissuebill.setCurrency("CNY");
        //币别修改获取逻辑
        omsSaleissuebill.setCurrency(receiptbill.getCurrency());
        //汇率
        omsSaleissuebill.setExchangerate(new BigDecimal(1));
        //厂编
        omsSaleissuebill.setFactorymake(receiptbill.getFactorymake());
        //来源单据
        omsSaleissuebill.setSrcbilltype("收货确认");
        omsSaleissuebill.setSrcbillnumber(receiptbill.getCode());
        //备注
        omsSaleissuebill.setDescription(receiptbill.getBuyernote());
        //创建时间
        omsSaleissuebill.setCreatetime(new Date());
        //是否外部客户
        omsSaleissuebill.setIsoutcustomer(0l);
        //来源系统
        omsSaleissuebill.setSrcsys(receiptbill.getSrcsys());

        /*设置采入单单据头数据*/


        //设置业务日期
        omsPurinwarehsbill.setBizdate(receiptbill.getReceiptdate());
        String PWbillNumber = omsTaskUtil.setBillNumber(omsPurinwarehsbill);
        //设置单据编号
        omsPurinwarehsbill.setBillnumber(PWbillNumber);
        //设置库存组织
        omsPurinwarehsbill.setStorageorgnumber(invoiceUnitNumber);
        omsPurinwarehsbill.setStorageorgname(invoiceUnit.getOrgname());
        //设置业务类型
        omsPurinwarehsbill.setBiztypenumber("111");
        omsPurinwarehsbill.setBiztypename("普通采购退货");
        //设置事务类型
        omsPurinwarehsbill.setTransactiontypenumber("005");
        omsPurinwarehsbill.setTransactiontypename("成本入库退货");
        //获取发货组织对应的供应商
        String inventoryNumber = inventoryUnit.getOrgnumber();
        BdSupplier bdSupplier = new BdSupplier();
        bdSupplier.setInternalcompanynumber(inventoryNumber);
        List<BdSupplier> bdSuppliers = supplierService.selectBdSupplierList(bdSupplier);
        if (StringUtils.isEmpty(bdSuppliers)) {
            stringBuffer.append("[没有找到内部公司编码为：" + inventoryNumber + "的供应商]");
            throw new RuntimeException(stringBuffer.toString());
        }
        bdSupplier = bdSuppliers.get(0);
        //设置供应商
        omsPurinwarehsbill.setSuppliernumber(bdSupplier.getSuppliernumber());
        omsPurinwarehsbill.setSuppliername(bdSupplier.getSuppliername());
        //设置成本中心
        omsPurinwarehsbill.setCostcenternumber("1.91");
        omsPurinwarehsbill.setCostcentername("关联单位");
        //设置记账公司
        omsPurinwarehsbill.setAccountcompanynumber(invoiceUnitNumber);
        omsPurinwarehsbill.setAccountcompanyname(invoiceUnit.getOrgname());
        //币别
//        omsPurinwarehsbill.setCurrency("CNY");
        //币别修改获取逻辑
        omsPurinwarehsbill.setCurrency(receiptbill.getCurrency());
        //汇率
        omsPurinwarehsbill.setExchangerate(BigDecimal.valueOf(1));
        //来源单据
        omsPurinwarehsbill.setSrcbilltype("收货确认");
        omsPurinwarehsbill.setSrcbillnumber(receiptbill.getCode());
        //备注
        omsPurinwarehsbill.setDescription(receiptbill.getBuyernote());
        //创建时间
        omsPurinwarehsbill.setCreatetime(new Date());
        omsPurinwarehsbill.setSrcsys(receiptbill.getSrcsys());



        //设置分录数据
        ArrayList<OmsSaleissuebillentry> saleissuebillentries = new ArrayList<>();
        ArrayList<OmsPurinwarehsbillentry> purinwarehsbillentries = new ArrayList<>();
        //获取销售出库单的发货仓库
        String wareHouse;
        String wareHouseName;
        //取上级组织的中转仓
            String inventorytransferwhnumber = inventoryUnit.getTransferwhnumber();
            String inventorytransferwhname = inventoryUnit.getTransferwhname();
            if (StringUtils.isEmpty(inventorytransferwhnumber)){
                stringBuffer.append("[组织：" + inventoryNumber + " 的中转仓为空！]");
                throw new RuntimeException(stringBuffer.toString());
            }
            wareHouse = inventorytransferwhnumber;
            wareHouseName = inventorytransferwhname;
//        //获取单据头的库存组织
//        String billHeadInventoryOrg = receiptbill.getInventoryorganizationcode();
//        if (billHeadInventoryOrg.equals(inventoryNumber) && billHeadInventoryOrg.equals(invoiceUnit.getFirstorgnumber())){
//            String facilitycode = receiptbill.getFacilitycode();
//            BdWarehouse bdWarehouse = new BdWarehouse();
//            bdWarehouse.setWarehousenumber(facilitycode);
//            List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
//            bdWarehouse = bdWarehouses.get(0);
//            String transferwhnumber = bdWarehouse.getTransferwhnumber();
//            if (StringUtils.isEmpty(transferwhnumber)) {
//                wareHouse = facilitycode;
//                wareHouseName = receiptbill.getFacilityname();
////                stringBuffer.append("[仓库：" + facilitycode + " 的在途仓库为空！]");
////                return 0;
//            }else {
//                wareHouse = transferwhnumber;
//                wareHouseName = bdWarehouse.getTransferwhname();
//            }
//        } else {
//            String transferwhnumber = inventoryUnit.getTransferwhnumber();
//            if (StringUtils.isEmpty(transferwhnumber)) {
//                stringBuffer.append("[组织：" + inventoryNumber + " 的中转仓为空！]");
//                throw new RuntimeException(stringBuffer.toString());
//            }
//            wareHouse = transferwhnumber;
//            wareHouseName = inventoryUnit.getTransferwhname();
//        }

        String pWWareHouseNumber;
        String pWWareHouseName;
        //如果下级组织等于单据上的库存组织，则取发货仓的在途仓，若不存在则取发货仓库编码
        //否则取下级组织的中转仓
        String inventoryorganizationcode = receiptbill.getInventoryorganizationcode();
        if (invoiceUnitNumber.equals(inventoryorganizationcode)){
            String facilitycode = receiptbill.getFacilitycode();
            String facilityname = receiptbill.getFacilityname();
            BdWarehouse bdWarehouse = new BdWarehouse();
            bdWarehouse.setWarehousenumber(facilitycode);
            List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
            bdWarehouse = bdWarehouses.get(0);
            String transferwhnumber = bdWarehouse.getTransferwhnumber();
            String transferwhname = bdWarehouse.getTransferwhname();
            if (StringUtils.isEmpty(transferwhnumber)){
                pWWareHouseNumber = facilitycode;
                pWWareHouseName = facilityname;
            }else {
                pWWareHouseNumber = transferwhnumber;
                pWWareHouseName = transferwhname;

            }
        }else {
            String transferwhnumber = invoiceUnit.getTransferwhnumber();
            String transferwhname = invoiceUnit.getTransferwhname();
            if (StringUtils.isEmpty(transferwhnumber)){
                stringBuffer.append("[组织：" + invoiceUnitNumber + " 的中转仓为空！]");
                throw new RuntimeException(stringBuffer.toString());
            }
            pWWareHouseNumber = transferwhnumber;
            pWWareHouseName = transferwhname;
        }
//        //获取采购入库单的仓库数据
//        //直接获取单据头storageOrgNumber的中转仓
//        String transferwhnumber = invoiceUnit.getTransferwhnumber();
//        if (StringUtils.isEmpty(transferwhnumber)) {
//            stringBuffer.append("[组织："+ invoiceUnitNumber +"的中转仓为空！]");
//            throw new RuntimeException(stringBuffer.toString());
//        }
//        pWWareHouseNumber = transferwhnumber;
//        pWWareHouseName = invoiceUnit.getTransferwhname();
//

        for (OmsReceiptbillentry omsReceiptbillentry : receiptbill.getOmsReceiptbillentryList()) {
            /*设置销出单分录数据*/


            OmsSaleissuebillentry omsSaleissuebillentry = new OmsSaleissuebillentry();
            //仓库
            omsSaleissuebillentry.setWarehousenumber(wareHouse);
            omsSaleissuebillentry.setWarehousename(wareHouseName);
            //物料
            String skucode = omsReceiptbillentry.getSkucode();
            String skuname = omsReceiptbillentry.getSkuname();
            omsSaleissuebillentry.setMaterialnumber(skucode);
            omsSaleissuebillentry.setMaterialname(skuname);
            //计量单位
            String unit = omsReceiptbillentry.getUnit();
            omsSaleissuebillentry.setUnitnumber(unit);
            //基本计量单位
            String baseunit = omsReceiptbillentry.getBaseunit();
            omsSaleissuebillentry.setBaseunitnumber(baseunit);
            //数量
            BigDecimal qty = omsReceiptbillentry.getReceivedqty();
            omsSaleissuebillentry.setQty(qty.multiply(new BigDecimal(-1)));
            //基本单位数量
            BigDecimal baseQty = omsReceiptbillentry.getBasereceivedqty();
            omsSaleissuebillentry.setBaseqty(baseQty.multiply(new BigDecimal(-1)));
            //系统含税单价
            BigDecimal systaxprice = omsReceiptbillentry.getSystaxprice();
            omsSaleissuebillentry.setSystaxprice(systaxprice);
            //含税单价
            BigDecimal taxPrice = omsTaskUtil.getTaxPrice(inventoryUnit, omsSaleissuebill.getCustomernumber(), omsSaleissuebill.getBizdate(), omsSaleissuebillentry.getMaterialnumber(), stringBuffer);
            if (StringUtils.isNull(taxPrice)) {
                throw new RuntimeException("[获取含税单价时出现异常：]" + stringBuffer.toString());
            }
            omsSaleissuebillentry.setTaxprice(taxPrice);
            //税率
            BigDecimal tempTaxrate = omsReceiptbillentry.getTaxrate();
            omsSaleissuebillentry.setTaxrate(tempTaxrate);
            BigDecimal taxrate = tempTaxrate;
            if (StringUtils.isNull(tempTaxrate)) {
                taxrate = BigDecimal.ZERO;
            }
            BigDecimal tempTaxRate = OmsTaskUtil.formatTaxRate(taxrate);
            //单价
            BigDecimal price = taxPrice.divide(tempTaxRate.add(BigDecimal.valueOf(1)),6, BigDecimal.ROUND_HALF_UP);
            omsSaleissuebillentry.setPrice(price);
            //税价合计
            BigDecimal taxAmount = taxPrice.multiply(qty).multiply(new BigDecimal(-1)).setScale(6, RoundingMode.HALF_UP);
            omsSaleissuebillentry.setTaxamount(taxAmount);
            //金额
//            BigDecimal amount = taxAmount.divide(tempTaxRate.add(BigDecimal.valueOf(1)),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal amount = price.multiply(qty).multiply(new BigDecimal(-1)).setScale(2,RoundingMode.HALF_UP);
            omsSaleissuebillentry.setAmount(amount);
            //税额
            BigDecimal tax = taxAmount.subtract(amount);
            omsSaleissuebillentry.setTax(tax);
            //是否赠品
            //内部销售没有赠品!
            Long isgift = omsReceiptbillentry.getIsgift();
            omsSaleissuebillentry.setIspresent(0L);
            //客户订单号
            omsSaleissuebillentry.setCustomerOrderNo(omsReceiptbillentry.getCustomerorder());
            //销售订单号
            omsSaleissuebillentry.setRefordercode(omsReceiptbillentry.getRefordercode());
            saleissuebillentries.add(omsSaleissuebillentry);


            /*设置采入单分录数据*/
            OmsPurinwarehsbillentry omsPurinwarehsbillentry = new OmsPurinwarehsbillentry();
            //仓库
            omsPurinwarehsbillentry.setWarehousenumber(pWWareHouseNumber);
            omsPurinwarehsbillentry.setWarehousename(pWWareHouseName);
            //物料
            omsPurinwarehsbillentry.setMaterialnumber(skucode);
            omsPurinwarehsbillentry.setMaterialname(skuname);
            //计量单位
            omsPurinwarehsbillentry.setUnitnumber(unit);
            omsPurinwarehsbillentry.setBaseunitnumber(baseunit);
            //数量
            omsPurinwarehsbillentry.setQty(qty.multiply(new BigDecimal(-1)));
            omsPurinwarehsbillentry.setBaseqty(baseQty.multiply(new BigDecimal(-1)));
            //含税单价
            omsPurinwarehsbillentry.setTaxprice(taxPrice);
            //税率
            omsPurinwarehsbillentry.setTaxrate(tempTaxrate);
            //单价
            omsPurinwarehsbillentry.setPrice(price);
            //税价合计
            omsPurinwarehsbillentry.setTaxamount(taxAmount);
            //金额
            omsPurinwarehsbillentry.setAmount(amount);
            //税额
            omsPurinwarehsbillentry.setTax(tax);
            //是否赠品
            //内部销售没有赠品!
            omsPurinwarehsbillentry.setIspresent(0L);

            purinwarehsbillentries.add(omsPurinwarehsbillentry);
        }
        omsSaleissuebill.setOmsSaleissuebillentryList(saleissuebillentries);
        omsPurinwarehsbill.setOmsPurinwarehsbillentryList(purinwarehsbillentries);
        try {
            int i = saleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
            if (i == 0) {
                throw new RuntimeException();
            }
        }catch (Exception e){
            stringBuffer.append("[插入销出单时出现错误！]");
            throw new RuntimeException(stringBuffer.toString() + e.getMessage());
        }
        try {
            int i1 = purinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
            if (i1 == 0) {
             throw new RuntimeException();
            }
        }catch (Exception e){
            stringBuffer.append("[插入采购入库单时出现错误！]");
            throw new RuntimeException(stringBuffer.toString() + e.getMessage());
        }
    }


    public void createFirstNodeBill(OmsReceiptbill receiptbill, OmsOrgunit inventoryUnit, OmsOrgunit invoiceUnit) {
        //判断两个组织的一级组织是否相等，如果相等就直接结束方法
        OmsOrgunit inventoryFirstorg = omsTaskUtil.getFirstOrg(inventoryUnit.getOrgnumber());
        OmsOrgunit invoiceFirstorg = omsTaskUtil.getFirstOrg(invoiceUnit.getOrgnumber());
        String inventoryFirstOrgnumber = inventoryFirstorg.getOrgnumber();
        String invoiceFirstOrgnumber = invoiceFirstorg.getOrgnumber();
        if (inventoryFirstOrgnumber.equals(invoiceFirstOrgnumber)){
            return;
        }
        //获取两个组织的是否子公司
        Long inventoryFirstorgIssub = inventoryFirstorg.getIssub();
        Long invoiceFirstorgIssub = invoiceFirstorg.getIssub();
        if (inventoryFirstorgIssub.equals(1L) && invoiceFirstorgIssub.equals(1L)){
            //如果两个公司的是否子公司都为是的话，那就要通过实业来进行交易
            //先销售给实业
            OmsOrgunit omsOrgunit = new OmsOrgunit();
            omsOrgunit.setOrgnumber("1.10.100");
            List<OmsOrgunit> omsOrgunits = orgunitService.selectOmsOrgunitList(omsOrgunit);
            omsOrgunit = omsOrgunits.get(0);
            try{
                //这里需要确定仓库的数据来源
                receiptBillTask.createFirstSIBillAndPWBill(inventoryFirstorg,omsOrgunit,receiptbill,new StringBuffer());
            }catch (Exception e){
                throw new RuntimeException("[生成库存一级组织销售到实业的销出采入单时出现异常：]" + e.getMessage());
            }
            try{
                //实业销售给销售一级组织
                receiptBillTask.createFirstSIBillAndPWBill(omsOrgunit,invoiceFirstorg,receiptbill,new StringBuffer());
            }catch (Exception e){
                throw new RuntimeException("[生成实业销售到销售一级组织的销出采入单时出现异常：]" + e.getMessage());
            }

        }else {
            try{
                //库存一级组织到销售一级组织
                receiptBillTask.createFirstSIBillAndPWBill(inventoryFirstorg,invoiceFirstorg,receiptbill,new StringBuffer());
            }catch (Exception e){
                throw new RuntimeException("[生成库存一级组织销售到销售一级组织的销出采入单时出现异常：]" + e.getMessage());
            }
        }

    }

    /**
     * 传入收货确认单、库存组织、销售组织和客户，生成一级组织之间的销售出货单和采购入库单
     * @param inventoryUnit 库存组织
     * @param invoiceUnit   销售组织
     * @param receiptbill   收货确认单
     * @param stringBuffer  错误信息
     * @return 生成结果
     */
    public void createFirstSIBillAndPWBill(OmsOrgunit inventoryUnit, OmsOrgunit invoiceUnit, OmsReceiptbill receiptbill, StringBuffer stringBuffer) {
        OmsSaleissuebill omsSaleissuebill = new OmsSaleissuebill();
        OmsPurinwarehsbill omsPurinwarehsbill = new OmsPurinwarehsbill();
        /*设置销出单单据头数据*/


        //业务日期
        omsSaleissuebill.setBizdate(receiptbill.getReceiptdate());
        String billNumber = omsTaskUtil.setBillNumber(omsSaleissuebill);
        //单据编号
        omsSaleissuebill.setBillnumber(billNumber);
        //库存组织
        omsSaleissuebill.setStorageorgnumber(inventoryUnit.getOrgnumber());
        omsSaleissuebill.setStorageorgname(inventoryUnit.getOrgname());
        //业务类型
        omsSaleissuebill.setBiztypenumber("210");
        omsSaleissuebill.setBiztypename("普通销售");
        //事务类型
        omsSaleissuebill.setTransactiontypenumber("012");
        omsSaleissuebill.setTransactiontypename("成本出库");
        //获取送货客户
        String invoiceUnitNumber = invoiceUnit.getOrgnumber();
        BdCustomer bdCustomer = new BdCustomer();
        bdCustomer.setInternalcompanynumber(invoiceUnitNumber);
        List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
        if (StringUtils.isEmpty(bdCustomers)) {
            stringBuffer.append("[没有找到内部公司编码为：" + invoiceUnitNumber + "的客户]");
            throw new RuntimeException(stringBuffer.toString());
        }
        bdCustomer = bdCustomers.get(0);
        //设置送货客户
        omsSaleissuebill.setCustomernumber(bdCustomer.getCustomernumber());
        omsSaleissuebill.setCustomername(bdCustomer.getCustomername());
        //记账公司
        omsSaleissuebill.setAccountcompanynumber(inventoryUnit.getOrgnumber());
        omsSaleissuebill.setAccountcompanyname(inventoryUnit.getOrgname());
        //成本中心
        omsSaleissuebill.setCostcenternumber("1.91");
        omsSaleissuebill.setCostcentername("关联单位");
//        //币别
//        omsSaleissuebill.setCurrency("CNY");
        //币别获取逻辑修改为获取上游单据类型
        omsSaleissuebill.setCurrency(receiptbill.getCurrency());
        //汇率
        omsSaleissuebill.setExchangerate(new BigDecimal(1));

        //厂编
        omsSaleissuebill.setFactorymake(receiptbill.getFactorymake());
        //来源单据
        omsSaleissuebill.setSrcbilltype("收货确认");
        omsSaleissuebill.setSrcbillnumber(receiptbill.getCode());
        //备注
        omsSaleissuebill.setDescription(receiptbill.getBuyernote());
        //创建时间
        omsSaleissuebill.setCreatetime(new Date());
        //是否外部客户
        omsSaleissuebill.setIsoutcustomer(0l);
        //来源系统
        omsSaleissuebill.setSrcsys(receiptbill.getSrcsys());

        /*设置采入单单据头数据*/


        //设置业务日期
        omsPurinwarehsbill.setBizdate(receiptbill.getReceiptdate());
        String PWbillNumber = omsTaskUtil.setBillNumber(omsPurinwarehsbill);
        //设置单据编号
        omsPurinwarehsbill.setBillnumber(PWbillNumber);
        //设置库存组织
        omsPurinwarehsbill.setStorageorgnumber(invoiceUnitNumber);
        omsPurinwarehsbill.setStorageorgname(invoiceUnit.getOrgname());
        //设置业务类型
        omsPurinwarehsbill.setBiztypenumber("110");
        omsPurinwarehsbill.setBiztypename("普通采购");
        //设置事务类型
        omsPurinwarehsbill.setTransactiontypenumber("004");
        omsPurinwarehsbill.setTransactiontypename("成本入库");
        //获取发货组织对应的供应商
        String inventoryNumber = inventoryUnit.getOrgnumber();
        BdSupplier bdSupplier = new BdSupplier();
        bdSupplier.setInternalcompanynumber(inventoryNumber);
        List<BdSupplier> bdSuppliers = supplierService.selectBdSupplierList(bdSupplier);
        if (StringUtils.isEmpty(bdSuppliers)) {
            stringBuffer.append("[没有找到内部公司编码为：" + inventoryNumber + "的供应商]");
            throw new RuntimeException(stringBuffer.toString());
        }
        bdSupplier = bdSuppliers.get(0);
        //设置供应商
        omsPurinwarehsbill.setSuppliernumber(bdSupplier.getSuppliernumber());
        omsPurinwarehsbill.setSuppliername(bdSupplier.getSuppliername());
        //设置成本中心
        omsPurinwarehsbill.setCostcenternumber("1.91");
        omsPurinwarehsbill.setCostcentername("关联单位");
        //设置记账公司
        omsPurinwarehsbill.setAccountcompanynumber(invoiceUnitNumber);
        omsPurinwarehsbill.setAccountcompanyname(invoiceUnit.getOrgname());
        //币别
//        omsPurinwarehsbill.setCurrency("CNY");
        //币别修改获取逻辑
        omsPurinwarehsbill.setCurrency(receiptbill.getCurrency());
        //汇率
        omsPurinwarehsbill.setExchangerate(BigDecimal.valueOf(1));
        //来源单据
        omsPurinwarehsbill.setSrcbilltype("收货确认");
        omsPurinwarehsbill.setSrcbillnumber(receiptbill.getCode());
        //备注
        omsPurinwarehsbill.setDescription(receiptbill.getBuyernote());
        //创建时间
        omsPurinwarehsbill.setCreatetime(new Date());
        omsPurinwarehsbill.setSrcsys(receiptbill.getSrcsys());



        //设置分录数据
        ArrayList<OmsSaleissuebillentry> saleissuebillentries = new ArrayList<>();
        ArrayList<OmsPurinwarehsbillentry> purinwarehsbillentries = new ArrayList<>();
        //获取销售出库单的发货仓库
        String wareHouse;
        String wareHouseName;
        //如果上级组织=库存组织编码，则取发货仓库facilityCode的在途仓，如果不存在就取发货仓；
        //否则取上级组织的中转仓。
        String inventoryorganizationcode = receiptbill.getInventoryorganizationcode();
        if (inventoryNumber.equals(inventoryorganizationcode)){
            String facilitycode = receiptbill.getFacilitycode();
            String facilityname = receiptbill.getFacilityname();
            if ("wdt".equals(receiptbill.getSrcsys())){
                wareHouse = facilitycode;
                wareHouseName = facilityname;
            }else {
                BdWarehouse bdWarehouse = new BdWarehouse();
                bdWarehouse.setWarehousenumber(facilitycode);
                List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
                bdWarehouse = bdWarehouses.get(0);
                String transferwhnumber = bdWarehouse.getTransferwhnumber();
                String transferwhname = bdWarehouse.getTransferwhname();
                if (StringUtils.isEmpty(transferwhnumber)) {
                    wareHouse = facilitycode;
                    wareHouseName = facilityname;
                } else {
                    wareHouse = transferwhnumber;
                    wareHouseName = transferwhname;

                }
            }
        }else {
            String transferwhnumber = inventoryUnit.getTransferwhnumber();
            String transferwhname = inventoryUnit.getTransferwhname();
            if (StringUtils.isEmpty(transferwhnumber)){
                stringBuffer.append("[组织：" + inventoryNumber + " 的中转仓为空！]");
                throw new RuntimeException(stringBuffer.toString());
            }
            wareHouse = transferwhnumber;
            wareHouseName = transferwhname;
        }



//        String facilitycode = receiptbill.getFacilitycode();
//        BdWarehouse bdWarehouse = new BdWarehouse();
//        bdWarehouse.setWarehousenumber(facilitycode);
//        List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
//        bdWarehouse = bdWarehouses.get(0);
//        String transferwhnumber = bdWarehouse.getTransferwhnumber();
//        if (StringUtils.isEmpty(transferwhnumber)) {
//            wareHouse = facilitycode;
//            wareHouseName = bdWarehouse.getWarehousename();
//        } else {
//            wareHouse = transferwhnumber;
//            wareHouseName = bdWarehouse.getTransferwhname();
//        }
        //获取采购入库单的仓库数据
        String pWWareHouse;
        String pWWareHouseName;
        //1、如果下级组织等于传过来的销售组织，且客户为内部客户（内部客户=1或者成本中心=1），则取传过来的收货仓库。
        //2、否则，下级组织的中转仓

        //逻辑修改：直接获取下级组织的中转仓
        String transferwhnumber1 = invoiceUnit.getTransferwhnumber();
        if (StringUtils.isEmpty(transferwhnumber1)) {
            stringBuffer.append("[组织：" + invoiceUnitNumber + "的中转仓为空！]");
            throw new RuntimeException(stringBuffer.toString());
        }
        pWWareHouse = transferwhnumber1;
        pWWareHouseName = invoiceUnit.getTransferwhname();


        for (OmsReceiptbillentry omsReceiptbillentry : receiptbill.getOmsReceiptbillentryList()) {
            /*设置销出单分录数据*/


            OmsSaleissuebillentry omsSaleissuebillentry = new OmsSaleissuebillentry();
            //仓库
            omsSaleissuebillentry.setWarehousenumber(wareHouse);
            omsSaleissuebillentry.setWarehousename(wareHouseName);
            //物料
            String skucode = omsReceiptbillentry.getSkucode();
            String skuname = omsReceiptbillentry.getSkuname();
            omsSaleissuebillentry.setMaterialnumber(skucode);
            omsSaleissuebillentry.setMaterialname(skuname);
            //计量单位
            String unit = omsReceiptbillentry.getUnit();
            omsSaleissuebillentry.setUnitnumber(unit);
            //基本计量单位
            String baseunit = omsReceiptbillentry.getBaseunit();
            omsSaleissuebillentry.setBaseunitnumber(baseunit);
            //数量
            BigDecimal qty = omsReceiptbillentry.getReceivedqty();
            omsSaleissuebillentry.setQty(qty);
            //基本单位数量
            BigDecimal baseQty = omsReceiptbillentry.getBasereceivedqty();
            omsSaleissuebillentry.setBaseqty(baseQty);
            //系统含税单价
            BigDecimal systaxprice = omsReceiptbillentry.getSystaxprice();
            omsSaleissuebillentry.setSystaxprice(systaxprice);
            //含税单价
            BigDecimal taxPrice = omsTaskUtil.getTaxPrice(inventoryUnit, omsSaleissuebill.getCustomernumber(), omsSaleissuebill.getBizdate(), omsSaleissuebillentry.getMaterialnumber(), stringBuffer);
            if (StringUtils.isNull(taxPrice)) {
                throw new RuntimeException(stringBuffer.toString());
            }
            omsSaleissuebillentry.setTaxprice(taxPrice);
            //税率
            BigDecimal tempTaxrate = omsReceiptbillentry.getTaxrate();
            omsSaleissuebillentry.setTaxrate(tempTaxrate);
            BigDecimal taxrate = tempTaxrate;
            if (StringUtils.isNull(tempTaxrate)) {
                taxrate = BigDecimal.ZERO;
            }
            BigDecimal tempTaxRate = OmsTaskUtil.formatTaxRate(taxrate);
            //单价
            BigDecimal price = taxPrice.divide(tempTaxRate.add(BigDecimal.valueOf(1)),6,BigDecimal.ROUND_HALF_UP);
            omsSaleissuebillentry.setPrice(price);
            //税价合计
            BigDecimal taxAmount = taxPrice.multiply(qty).setScale(6, RoundingMode.HALF_UP);
            omsSaleissuebillentry.setTaxamount(taxAmount);
            //金额
//            BigDecimal amount = taxAmount.divide(tempTaxRate.add(BigDecimal.valueOf(1)),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal amount = price.multiply(qty).setScale(2, RoundingMode.HALF_UP);
            omsSaleissuebillentry.setAmount(amount);
            //税额
            BigDecimal tax = taxAmount.subtract(amount);
            omsSaleissuebillentry.setTax(tax);
            //是否赠品
            //内部销售没有赠品!
            Long isgift = omsReceiptbillentry.getIsgift();
            omsSaleissuebillentry.setIspresent(0L);
            //客户订单号
            omsSaleissuebillentry.setCustomerOrderNo(omsReceiptbillentry.getCustomerorder());
            //销售订单号
            omsSaleissuebillentry.setRefordercode(omsReceiptbillentry.getRefordercode());
            saleissuebillentries.add(omsSaleissuebillentry);


            /*设置采入单分录数据*/
            OmsPurinwarehsbillentry omsPurinwarehsbillentry = new OmsPurinwarehsbillentry();
            //仓库
            omsPurinwarehsbillentry.setWarehousenumber(pWWareHouse);
            omsPurinwarehsbillentry.setWarehousename(pWWareHouseName);
            //物料
            omsPurinwarehsbillentry.setMaterialnumber(skucode);
            omsPurinwarehsbillentry.setMaterialname(skuname);
            //计量单位
            omsPurinwarehsbillentry.setUnitnumber(unit);
            omsPurinwarehsbillentry.setBaseunitnumber(baseunit);
            //数量
            omsPurinwarehsbillentry.setQty(qty);
            omsPurinwarehsbillentry.setBaseqty(baseQty);
            //含税单价
            omsPurinwarehsbillentry.setTaxprice(taxPrice);
            //税率
            omsPurinwarehsbillentry.setTaxrate(tempTaxrate);
            //单价
            omsPurinwarehsbillentry.setPrice(price);
            //税价合计
            omsPurinwarehsbillentry.setTaxamount(taxAmount);
            //金额
            omsPurinwarehsbillentry.setAmount(amount);
            //税额
            omsPurinwarehsbillentry.setTax(tax);
            //是否赠品
            //内部销售没有赠品!
            omsPurinwarehsbillentry.setIspresent(0L);

            purinwarehsbillentries.add(omsPurinwarehsbillentry);
        }
        omsSaleissuebill.setOmsSaleissuebillentryList(saleissuebillentries);
        omsPurinwarehsbill.setOmsPurinwarehsbillentryList(purinwarehsbillentries);

        int i = saleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
        if (i == 0) {
            stringBuffer.append("[插入销出单时出现错误！]");
            throw new RuntimeException(stringBuffer.toString());
        }
        int i1 = purinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
        if (i1 == 0) {
            stringBuffer.append("[插入采购入库单时出现错误！]");
            throw new RuntimeException(stringBuffer.toString());
        }
    }



    public void sellDown(OmsReceiptbill receiptbill,OmsOrgunit invoiceUnit,OmsOrgunit salesInitialNode){
        //如果销售组织等于销售的最初节点，直接结束方法
        if (invoiceUnit.getOrgnumber().equals(salesInitialNode.getOrgnumber())){
            return;
        }
        //获取所有的节点组织
        ArrayList<OmsOrgunit> allTransOrg;
        try {
            allTransOrg = receiptBillTask.getAllTransOrg(invoiceUnit,salesInitialNode);
        }catch (Exception e){
            throw new RuntimeException("[获取销售组织到销售的最初节点的组织集合时出现异常：]" + e.getMessage());
        }
        //依次将两个组织传入方法进行生成销出采入单
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < allTransOrg.size() - 1; i++) {
            try {
                //需要确定仓库的数据来源
                receiptBillTask.createTransitionSIBillAndPWBill(allTransOrg.get(i), allTransOrg.get(i + 1), receiptbill, stringBuffer);
            }catch (Exception e){
                throw new RuntimeException("[销售的最初节点向销售组织生成销出采入单时出现异常：]" + e.getMessage());
            }
        }
    }

    /**
     * 从销售的最初节点销售到销售组织
     * @param inventoryUnit
     * @param invoiceUnit
     * @param receiptbill
     * @param stringBuffer
     */
    public void createTransitionSIBillAndPWBill(OmsOrgunit inventoryUnit, OmsOrgunit invoiceUnit, OmsReceiptbill receiptbill, StringBuffer stringBuffer) {
        OmsSaleissuebill omsSaleissuebill = new OmsSaleissuebill();
        OmsPurinwarehsbill omsPurinwarehsbill = new OmsPurinwarehsbill();
        /*设置销出单单据头数据*/

        //业务日期
        omsSaleissuebill.setBizdate(receiptbill.getReceiptdate());
        String billNumber = omsTaskUtil.setBillNumber(omsSaleissuebill);
        //单据编号
        omsSaleissuebill.setBillnumber(billNumber);
        //库存组织
        omsSaleissuebill.setStorageorgnumber(inventoryUnit.getOrgnumber());
        omsSaleissuebill.setStorageorgname(inventoryUnit.getOrgname());
        //业务类型
        omsSaleissuebill.setBiztypenumber("210");
        omsSaleissuebill.setBiztypename("普通销售");
        //事务类型
        omsSaleissuebill.setTransactiontypenumber("012");
        omsSaleissuebill.setTransactiontypename("成本出库");
        //获取送货客户
        String invoiceUnitNumber = invoiceUnit.getOrgnumber();
        BdCustomer bdCustomer = new BdCustomer();
        bdCustomer.setInternalcompanynumber(invoiceUnitNumber);
        List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
        if (StringUtils.isEmpty(bdCustomers)) {
            stringBuffer.append("[没有找到内部公司编码为：" + invoiceUnitNumber + "的客户]");
            throw new RuntimeException(stringBuffer.toString());
        }
        bdCustomer = bdCustomers.get(0);
        //设置送货客户
        omsSaleissuebill.setCustomernumber(bdCustomer.getCustomernumber());
        omsSaleissuebill.setCustomername(bdCustomer.getCustomername());
        //记账公司
        omsSaleissuebill.setAccountcompanynumber(inventoryUnit.getOrgnumber());
        omsSaleissuebill.setAccountcompanyname(inventoryUnit.getOrgname());
        //成本中心
        omsSaleissuebill.setCostcenternumber("1.91");
        omsSaleissuebill.setCostcentername("关联单位");
        //币别
//        omsSaleissuebill.setCurrency("CNY");
        //币别修改获取逻辑
        omsSaleissuebill.setCurrency(receiptbill.getCurrency());
        //汇率
        omsSaleissuebill.setExchangerate(new BigDecimal(1));
        //厂编
        omsSaleissuebill.setFactorymake(receiptbill.getFactorymake());
        //来源单据
        omsSaleissuebill.setSrcbilltype("收货确认");
        omsSaleissuebill.setSrcbillnumber(receiptbill.getCode());
        //备注
        omsSaleissuebill.setDescription(receiptbill.getBuyernote());
        //创建时间
        omsSaleissuebill.setCreatetime(new Date());
        //是否外部客户
        omsSaleissuebill.setIsoutcustomer(0l);
        //来源系统
        omsSaleissuebill.setSrcsys(receiptbill.getSrcsys());


        /*设置采入单单据头数据*/


        //设置业务日期
        omsPurinwarehsbill.setBizdate(receiptbill.getReceiptdate());
        String PWbillNumber = omsTaskUtil.setBillNumber(omsPurinwarehsbill);
        //设置单据编号
        omsPurinwarehsbill.setBillnumber(PWbillNumber);
        //设置库存组织
        omsPurinwarehsbill.setStorageorgnumber(invoiceUnitNumber);
        omsPurinwarehsbill.setStorageorgname(invoiceUnit.getOrgname());
        //设置业务类型
        omsPurinwarehsbill.setBiztypenumber("110");
        omsPurinwarehsbill.setBiztypename("普通采购");
        //设置事务类型
        omsPurinwarehsbill.setTransactiontypenumber("004");
        omsPurinwarehsbill.setTransactiontypename("成本入库");
        //获取发货组织对应的供应商
        String inventoryNumber = inventoryUnit.getOrgnumber();
        BdSupplier bdSupplier = new BdSupplier();
        bdSupplier.setInternalcompanynumber(inventoryNumber);
        List<BdSupplier> bdSuppliers = supplierService.selectBdSupplierList(bdSupplier);
        if (StringUtils.isEmpty(bdSuppliers)) {
            stringBuffer.append("[没有找到内部公司编码为：" + inventoryNumber + "的供应商]");
            throw new RuntimeException(stringBuffer.toString());
        }
        bdSupplier = bdSuppliers.get(0);
        //设置供应商
        omsPurinwarehsbill.setSuppliernumber(bdSupplier.getSuppliernumber());
        omsPurinwarehsbill.setSuppliername(bdSupplier.getSuppliername());
        //设置成本中心
        omsPurinwarehsbill.setCostcenternumber("1.91");
        omsPurinwarehsbill.setCostcentername("关联单位");
        //设置记账公司
        omsPurinwarehsbill.setAccountcompanynumber(invoiceUnitNumber);
        omsPurinwarehsbill.setAccountcompanyname(invoiceUnit.getOrgname());
        //币别
//        omsPurinwarehsbill.setCurrency("CNY");
        //币别修改获取逻辑
        omsPurinwarehsbill.setCurrency(receiptbill.getCurrency());
        //汇率
        omsPurinwarehsbill.setExchangerate(BigDecimal.valueOf(1));
        //来源单据
        omsPurinwarehsbill.setSrcbilltype("收货确认");
        omsPurinwarehsbill.setSrcbillnumber(receiptbill.getCode());
        //备注
        omsPurinwarehsbill.setDescription(receiptbill.getBuyernote());
        //创建时间
        omsPurinwarehsbill.setCreatetime(new Date());
        omsPurinwarehsbill.setSrcsys(receiptbill.getSrcsys());



        //设置分录数据
        ArrayList<OmsSaleissuebillentry> saleissuebillentries = new ArrayList<>();
        ArrayList<OmsPurinwarehsbillentry> purinwarehsbillentries = new ArrayList<>();
        //获取销售出库单的发货仓库
        String wareHouse;
        String wareHouseName;
        //获取单据头的库存组织
        String billHeadInventoryOrg = receiptbill.getInventoryorganizationcode();
        if (billHeadInventoryOrg.equals(inventoryNumber) && billHeadInventoryOrg.equals(invoiceUnit.getFirstorgnumber())){
            String facilitycode = receiptbill.getFacilitycode();
            BdWarehouse bdWarehouse = new BdWarehouse();
            bdWarehouse.setWarehousenumber(facilitycode);
            List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
            bdWarehouse = bdWarehouses.get(0);
            String transferwhnumber = bdWarehouse.getTransferwhnumber();
            if (StringUtils.isEmpty(transferwhnumber)) {
                wareHouse = facilitycode;
                wareHouseName = receiptbill.getFacilityname();
//                stringBuffer.append("[仓库：" + facilitycode + " 的在途仓库为空！]");
//                return 0;
            }else {
                wareHouse = transferwhnumber;
                wareHouseName = bdWarehouse.getTransferwhname();
            }

        } else {
            String transferwhnumber = inventoryUnit.getTransferwhnumber();
            if (StringUtils.isEmpty(transferwhnumber)) {
                stringBuffer.append("[组织：" + inventoryNumber + " 的中转仓为空！]");
                throw new RuntimeException(stringBuffer.toString());
            }
            wareHouse = transferwhnumber;
            wareHouseName = inventoryUnit.getTransferwhname();
        }

        String pWWareHouseNumber;
        String pWWareHouseName;
        //获取采购入库单的仓库数据
        //直接获取单据头storageOrgNumber的中转仓
        String transferwhnumber = invoiceUnit.getTransferwhnumber();
        if (StringUtils.isEmpty(transferwhnumber)) {
            stringBuffer.append("[组织："+ invoiceUnitNumber +"的中转仓为空！]");
            throw new RuntimeException(stringBuffer.toString());
        }
        pWWareHouseNumber = transferwhnumber;
        pWWareHouseName = invoiceUnit.getTransferwhname();


        for (OmsReceiptbillentry omsReceiptbillentry : receiptbill.getOmsReceiptbillentryList()) {
            /*设置销出单分录数据*/


            OmsSaleissuebillentry omsSaleissuebillentry = new OmsSaleissuebillentry();
            //仓库
            omsSaleissuebillentry.setWarehousenumber(wareHouse);
            omsSaleissuebillentry.setWarehousename(wareHouseName);
            //物料
            String skucode = omsReceiptbillentry.getSkucode();
            String skuname = omsReceiptbillentry.getSkuname();
            omsSaleissuebillentry.setMaterialnumber(skucode);
            omsSaleissuebillentry.setMaterialname(skuname);
            //计量单位
            String unit = omsReceiptbillentry.getUnit();
            omsSaleissuebillentry.setUnitnumber(unit);
            //基本计量单位
            String baseunit = omsReceiptbillentry.getBaseunit();
            omsSaleissuebillentry.setBaseunitnumber(baseunit);
            //数量
            BigDecimal qty = omsReceiptbillentry.getReceivedqty();
            omsSaleissuebillentry.setQty(qty);
            //基本单位数量
            BigDecimal baseQty = omsReceiptbillentry.getBasereceivedqty();
            omsSaleissuebillentry.setBaseqty(baseQty);
            //系统含税单价
            BigDecimal systaxprice = omsReceiptbillentry.getSystaxprice();
            omsSaleissuebillentry.setSystaxprice(systaxprice);
            //含税单价
            BigDecimal taxPrice = omsTaskUtil.getTaxPrice(inventoryUnit, omsSaleissuebill.getCustomernumber(), omsSaleissuebill.getBizdate(), omsSaleissuebillentry.getMaterialnumber(), stringBuffer);
            if (StringUtils.isNull(taxPrice)) {
                throw new RuntimeException(stringBuffer.toString());
            }
            omsSaleissuebillentry.setTaxprice(taxPrice);
            //税率
            BigDecimal tempTaxrate = omsReceiptbillentry.getTaxrate();
            omsSaleissuebillentry.setTaxrate(tempTaxrate);
            BigDecimal taxrate = tempTaxrate;
            if (StringUtils.isNull(tempTaxrate)) {
                taxrate = BigDecimal.ZERO;
            }
            BigDecimal tempTaxRate = OmsTaskUtil.formatTaxRate(taxrate);
            //单价
            BigDecimal price = taxPrice.divide(tempTaxRate.add(BigDecimal.valueOf(1)),6, BigDecimal.ROUND_HALF_UP);
            omsSaleissuebillentry.setPrice(price);
            //税价合计
            BigDecimal taxAmount = taxPrice.multiply(qty).setScale(6,RoundingMode.HALF_UP);
            omsSaleissuebillentry.setTaxamount(taxAmount);
            //金额
//            BigDecimal amount = taxAmount.divide(tempTaxRate.add(BigDecimal.valueOf(1)),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal amount = price.multiply(qty).setScale(2,RoundingMode.HALF_UP);
            omsSaleissuebillentry.setAmount(amount);
            //税额
            BigDecimal tax = taxAmount.subtract(amount);
            omsSaleissuebillentry.setTax(tax);
            //是否赠品
            //内部销售没有赠品!
            Long isgift = omsReceiptbillentry.getIsgift();
            omsSaleissuebillentry.setIspresent(0L);
            //客户订单号
            omsSaleissuebillentry.setCustomerOrderNo(omsReceiptbillentry.getCustomerorder());
            //销售订单号
            omsSaleissuebillentry.setRefordercode(omsReceiptbillentry.getRefordercode());
            saleissuebillentries.add(omsSaleissuebillentry);


            /*设置采入单分录数据*/
            OmsPurinwarehsbillentry omsPurinwarehsbillentry = new OmsPurinwarehsbillentry();
            //仓库
            omsPurinwarehsbillentry.setWarehousenumber(pWWareHouseNumber);
            omsPurinwarehsbillentry.setWarehousename(pWWareHouseName);
            //物料
            omsPurinwarehsbillentry.setMaterialnumber(skucode);
            omsPurinwarehsbillentry.setMaterialname(skuname);
            //计量单位
            omsPurinwarehsbillentry.setUnitnumber(unit);
            omsPurinwarehsbillentry.setBaseunitnumber(baseunit);
            //数量
            omsPurinwarehsbillentry.setQty(qty);
            omsPurinwarehsbillentry.setBaseqty(baseQty);
            //含税单价
            omsPurinwarehsbillentry.setTaxprice(taxPrice);
            //税率
            omsPurinwarehsbillentry.setTaxrate(tempTaxrate);
            //单价
            omsPurinwarehsbillentry.setPrice(price);
            //税价合计
            omsPurinwarehsbillentry.setTaxamount(taxAmount);
            //金额
            omsPurinwarehsbillentry.setAmount(amount);
            //税额
            omsPurinwarehsbillentry.setTax(tax);
            //是否赠品
            //内部销售没有赠品!
            omsPurinwarehsbillentry.setIspresent(0L);

            purinwarehsbillentries.add(omsPurinwarehsbillentry);
        }
        omsSaleissuebill.setOmsSaleissuebillentryList(saleissuebillentries);
        omsPurinwarehsbill.setOmsPurinwarehsbillentryList(purinwarehsbillentries);

        int i = saleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
        if (i == 0) {
            stringBuffer.append("[插入销出单时出现错误！]");
            throw new RuntimeException(stringBuffer.toString());
        }
        int i1 = purinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
        if (i1 == 0) {
            stringBuffer.append("[插入采购入库单时出现错误！]");
            throw new RuntimeException(stringBuffer.toString());
        }
    }


    public void transferToReceipt(OmsOrgunit invoiceUnit,BdCustomer bdCustomer,OmsReceiptbill receiptbill,boolean isOutCustomer,StringBuffer stringBuffer){
        //如果是内部客户，销售组织的中转仓不等于收获仓，生成调拨单
        if (isOutCustomer) {
            return;
        }
        String transferwhnumber = invoiceUnit.getTransferwhnumber();
        String receivefacilitycode = receiptbill.getReceivefacilitycode();
        if (transferwhnumber.equals(receivefacilitycode)) {
            return;
        }
        try{
            //生成一张调拨单，由中转仓调拨到收获仓
            receiptBillTask.createInvoiceUnitTransferBill(invoiceUnit, bdCustomer, receiptbill, stringBuffer);
        }catch (Exception e){
            throw new RuntimeException("[生成由销售组织的中转仓到收货仓的库存调拨单时出现异常：]" + e.getMessage());
        }
    }



    /**
     * 传入销售组织、销售组织对应的内部客户、收货确认单
     * 生成一张调拨单
     * @param invoiceUnit
     * @param bdCustomer
     * @param receiptbill
     * @param stringBuffer
     * @return
     */
    public void createInvoiceUnitTransferBill(OmsOrgunit invoiceUnit, BdCustomer bdCustomer, OmsReceiptbill receiptbill, StringBuffer stringBuffer){
        OmsStocktransferbill omsStocktransferbill = new OmsStocktransferbill();
        // 开始设置单据头数据

        //业务日期
        omsStocktransferbill.setBizdate(receiptbill.getReceiptdate());
        omsStocktransferbill.setBizdate(receiptbill.getReceiptdate());
        //单据编号
        String billNumber = omsTaskUtil.setBillNumber(omsStocktransferbill);
        omsStocktransferbill.setBillnumber(billNumber);
        //业务类型
        omsStocktransferbill.setBiztypenumber("331");
        omsStocktransferbill.setBiztypename("跨仓库调拨（成本价）");
        //获取库存组织
        String orgnumber = invoiceUnit.getOrgnumber();
        String orgname = invoiceUnit.getOrgname();
        //调出仓库组织
        omsStocktransferbill.setIssuestorageorgnumber(orgnumber);
        omsStocktransferbill.setIssuestorageorgname(orgname);
        //调入库存组织
        omsStocktransferbill.setReceiptstorageorgnumber(orgnumber);
        omsStocktransferbill.setReceiptstorageorgname(orgname);
        //调出成本中心
        omsStocktransferbill.setOutcostcenternumber(receiptbill.getCostcentercode());
        omsStocktransferbill.setOutcostcentername(receiptbill.getCostcentername());
        //调出记账公司
        omsStocktransferbill.setOutaccountcompanynumber(orgnumber);
        omsStocktransferbill.setOutaccountcompanyname(orgname);
        //调入成本中心
        String costcenternumber = bdCustomer.getCostcenternumber();
//        if (StringUtils.isEmpty(costcenternumber)) {
//            stringBuffer.append("[客户：" + bdCustomer.getCustomernumber() + " 的成本中心为空！]");
//            return 0;
//        }
        omsStocktransferbill.setIncostcenternumber(costcenternumber);
        omsStocktransferbill.setIncostcentername(bdCustomer.getCostcentername());
        //调入记账公司
        omsStocktransferbill.setInaccountcompanynumber(orgnumber);
        omsStocktransferbill.setInaccountcompanyname(orgname);
        //币别
        omsStocktransferbill.setCurrency(receiptbill.getCurrency());
        //汇率
        omsStocktransferbill.setExchangerate(receiptbill.getExchangerate());
        //来源单据
        omsStocktransferbill.setSrcbilltype("收货确认");
        omsStocktransferbill.setSrcbillnumber(receiptbill.getCode());
        //备注
        omsStocktransferbill.setDescription(receiptbill.getBuyernote());
        //创建时间
        omsStocktransferbill.setCreatetime(new Date());
        //来源系统
        omsStocktransferbill.setSrcsys(receiptbill.getSrcsys());

        //设置分录数据
        ArrayList<OmsStocktransferbillentry> stocktransferbillentries = new ArrayList<>();
        for (OmsReceiptbillentry omsReceiptbillentry : receiptbill.getOmsReceiptbillentryList()) {
            OmsStocktransferbillentry omsStocktransferbillentry = new OmsStocktransferbillentry();
            //物料
            omsStocktransferbillentry.setMaterialnumber(omsReceiptbillentry.getSkucode());
            omsStocktransferbillentry.setMaterialname(omsReceiptbillentry.getSkuname());
            //调出仓库
            omsStocktransferbillentry.setIssuewarehousenumber(invoiceUnit.getTransferwhnumber());
            omsStocktransferbillentry.setIssuewarehousename(invoiceUnit.getTransferwhname());
            //调入仓库
            omsStocktransferbillentry.setReceiptwarehousenumber(receiptbill.getReceivefacilitycode());
            omsStocktransferbillentry.setReceiptwarehousename(receiptbill.getReceivefacilityname());
            //计量单位
            omsStocktransferbillentry.setUnitnumber(omsReceiptbillentry.getUnit());
            //基本计量单位
            omsStocktransferbillentry.setBaseunitnumber(omsReceiptbillentry.getBaseunit());
            //数量
            omsStocktransferbillentry.setQty(omsReceiptbillentry.getReceivedqty());
            //基本单位数量
            omsStocktransferbillentry.setBaseqty(omsReceiptbillentry.getBasereceivedqty());
            //计划调出日期
            omsStocktransferbillentry.setIssueplandate(receiptbill.getReceiptdate());
            //计划调入日期
            omsStocktransferbillentry.setReceiptplandate(receiptbill.getReceiptdate());
            //赠品
            omsStocktransferbillentry.setIspresent(omsReceiptbillentry.getIsgift());

            stocktransferbillentries.add(omsStocktransferbillentry);
        }
        omsStocktransferbill.setOmsStocktransferbillentryList(stocktransferbillentries);
        int i = stocktransferbillService.insertOmsStocktransferbill(omsStocktransferbill);
        if (i == 0) {
            stringBuffer.append("[插入库存调拨单时出现错误！]");
            throw new RuntimeException(stringBuffer.toString());
        }
    }


    /**
     * 获取A节点到B节点中间的所有节点
     * @param nodeOrg 需要获取一级组织到本身的组织集合的组织
     * @return 存储了从一级组织开始到本身的组织集合
     */
    public ArrayList<OmsOrgunit> getAllTransOrg(OmsOrgunit nodeOrg,OmsOrgunit returnFinalNode){
        //准备一个集合，用来存储中间过度的组织,统一用于后续生成采入销出单
        //先获取销售组织的一级组织，记为firstOrg
        //再获取销售组织的上级组织，记为fatherOrg
        //开始循环,使用while循环,判断条件为firstOrg与fatherOrg是否相等
        //循环内容为：获取fatierOrg的上级组织，并将值赋值给
        //如果不相同则将fatherOrg加入到集合中
        //如果相等结束循环。
        //将一级组织生成销出单，销售组织生成采入单
        //过渡组织集合生成采入、销出单

        ArrayList<OmsOrgunit> transitionOrg = new ArrayList<>();
        String returnFinalNodeOrgnumber = returnFinalNode.getOrgnumber();
        String parentorgnumber = nodeOrg.getParentorgnumber();
        OmsOrgunit parentUnit = new OmsOrgunit();
        parentUnit.setOrgnumber(parentorgnumber);
        List<OmsOrgunit> omsOrgunits1 = orgunitService.selectOmsOrgunitList(parentUnit);
        if (StringUtils.isEmpty(omsOrgunits1)) {
            throw new RuntimeException("[没有找到组织：" + parentorgnumber + "]");
        }
        parentUnit = omsOrgunits1.get(0);
        while (!returnFinalNodeOrgnumber.equals(parentorgnumber)) {
            transitionOrg.add(0, parentUnit);
            OmsOrgunit tempOrgUnit = new OmsOrgunit();
            tempOrgUnit.setOrgnumber(parentUnit.getParentorgnumber());
            List<OmsOrgunit> tempOrgUnits = orgunitService.selectOmsOrgunitList(tempOrgUnit);
            if (StringUtils.isEmpty(tempOrgUnits)) {
                throw new RuntimeException("[没有找到组织：" + tempOrgUnit.getOrgnumber() + "]");
            }
            parentUnit = tempOrgUnits.get(0);
            parentorgnumber = parentUnit.getOrgnumber();
        }
        transitionOrg.add(0, returnFinalNode);
        transitionOrg.add(nodeOrg);
        return transitionOrg;
    }


}
